package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

type MediaFile struct {
	ID        int    `json:"id"`
	Directory string `json:"directory"`
	M3U8Path  string `json:"m3u8_path"`
	JpgPath   string `json:"jpg_path"`
	Title     string `json:"title"`
	Classify  string `json:"classify"`
	CreatedAt string `json:"created_at"`
}

type Response struct {
	Data       []MediaFile `json:"data"`
	TotalCount int         `json:"total"`
	Page       int         `json:"page"`
	PageSize   int         `json:"pageSize"`
}

func main() {
	db, err := sql.Open("mysql", "root:123123@tcp(192.168.1.10:3306)/videos?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		log.Fatal("❌ 数据库连接失败:", err)
	}
	defer db.Close()

	// ✅ 支持分页、分类、搜索
	http.HandleFunc("/api/videos", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Content-Type", "application/json")

		page, _ := strconv.Atoi(r.URL.Query().Get("page"))
		pageSize, _ := strconv.Atoi(r.URL.Query().Get("pageSize"))
		if page <= 0 {
			page = 1
		}
		if pageSize <= 0 {
			pageSize = 10
		}

		search := strings.TrimSpace(r.URL.Query().Get("search"))
		classify := strings.TrimSpace(r.URL.Query().Get("classify"))

		// SQL 条件拼接
		conditions := []string{"1=1"}
		args := []interface{}{}

		if search != "" {
			conditions = append(conditions, "title LIKE ?")
			args = append(args, "%"+search+"%")
		}
		if classify != "" {
			conditions = append(conditions, "classify = ?")
			args = append(args, classify)
		}

		whereSQL := "WHERE " + strings.Join(conditions, " AND ")
		offset := (page - 1) * pageSize

		// 统计总数
		countSQL := fmt.Sprintf("SELECT COUNT(*) FROM media_files %s", whereSQL)
		var total int
		err := db.QueryRow(countSQL, args...).Scan(&total)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}

		// 查询分页数据
		querySQL := fmt.Sprintf(
			"SELECT id, directory, m3u8_path, jpg_path, title, classify, created_at FROM media_files %s ORDER BY created_at DESC LIMIT ? OFFSET ?",
			whereSQL,
		)
		args = append(args, pageSize, offset)
		rows, err := db.Query(querySQL, args...)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		defer rows.Close()

		var results []MediaFile
		for rows.Next() {
			var m MediaFile
			if err := rows.Scan(&m.ID, &m.Directory, &m.M3U8Path, &m.JpgPath, &m.Title, &m.Classify, &m.CreatedAt); err == nil {
				results = append(results, m)
			}
		}

		json.NewEncoder(w).Encode(Response{
			Data:       results,
			TotalCount: total,
			Page:       page,
			PageSize:   pageSize,
		})
	})

	// 静态文件服务
	http.Handle("/data/", http.StripPrefix("/data/", http.FileServer(http.Dir("/data"))))
	http.Handle("/data2/", http.StripPrefix("/data2/", http.FileServer(http.Dir("/data2"))))
	http.Handle("/movies/", http.StripPrefix("/movies/", http.FileServer(http.Dir("/movies"))))
	http.Handle("/music/", http.StripPrefix("/music/", http.FileServer(http.Dir("/music"))))

	log.Println("✅ 后端服务启动：http://127.0.0.1:6900")
	http.ListenAndServe(":6900", nil)
}
